<?php

Class Utils
{
	static function ShowError($errorCode, $errorMessage = "")
	{
		if(empty($errorMessage)) {
			$errorMessage = ErrorDefine::errorMessage($errorCode);
		}
		$message = array(
				'error_code' => $errorCode,
				'error_message' => $errorMessage
				);
		self::ShowMessageDiy($message);
	}
	
    //只需传$data
	static function ShowMessage($data = '',$error_code =0,$error_message ='')
	{
	    if ($data){
	        $message = array(
	            'error_code' => $error_code,
	            'error_message' => $error_message,
	            'data' => $data
	        );
	    }else {
	        $message = array(
	            'error_code' => $error_code,
	            'error_message' => $error_message,
	        );
	    }
	    
	
	    $http_body = stripslashes(self::decodeUnicode(json_encode($message)));
	    $content_len = strlen($http_body);
	    header("Content-type: application/json;charset=UTF-8");
	    header("Content-Length: $content_len");
	    echo $http_body;
	}

	static function ShowMessageDiy($message = null)
	{
		if($message == null) {
			$message = array(
					'error_code' => 0,
					'error_message' => '',
			        'data' => ''
					);
		}

		$http_body = stripslashes(self::decodeUnicode(json_encode($message)));
		$content_len = strlen($http_body);
		header("Content-type: application/json;charset=UTF-8");
		header("Content-Length: $content_len");
		echo $http_body;
	}
	
	static function ShowMessageXML($message = null)
	{
	    if($message == null) {
	        $message = array(
	            'error_code' => 0,
	            'error_message' => ''
	        );
	    }
	
	    $http_body = self::ArrayToXML($message);
	    $content_len = strlen($http_body);
	    header("Content-type: application/xml");
	    header("Content-Length: $content_len");
	    echo $http_body;
	}

	static function GetClientIP()
	{
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		} elseif (isset($_SERVER["HTTP_CLIENTIP"])) {
			$ip = $_SERVER["HTTP_CLIENTIP"];
		} elseif (isset($_SERVER["REMOTE_ADDR"])) {
			$ip = $_SERVER["REMOTE_ADDR"];
		} elseif (getenv("HTTP_X_FORWARDED_FOR")) {
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		} elseif (getenv("HTTP_CLIENTIP")) {
			$ip = getenv("HTTP_CLIENTIP");
		} elseif (getenv("REMOTE_ADDR")) {
			$ip = getenv("REMOTE_ADDR");
		} else {
			$ip = "127.0.0.1";
		}
//		var_dump($ip);
//		$pos = strpos($ip, ',');
//		var_dump($pos);
//		if ($pos > 0) $ip = substr($ip, 0, $pos);
		return trim($ip);
	}

	static function Num2IP($num)
	{
		$tmp = (double)$num;
		return sprintf('%u.%u.%u.%u', $tmp & 0xFF, (($tmp >> 8) & 0xFF),
				(($tmp >> 16) & 0xFF), (($tmp >> 24) & 0xFF));
	}

	static function IP2Num($ip)
	{
		if (!preg_match('/^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/is', $ip)) {
			return 0;
		}
		$n = ip2long($ip);
		/** convert to network order */
		$n =       (($n & 0xFF) << 24)
			| ((($n >> 8) & 0xFF) << 16)
			| ((($n >> 16) & 0xFF) << 8)
			| (($n >> 24) & 0xFF);
		return $n;
	}

	static function IsInteger($value) {
		return is_numeric($value) && is_int($value+0);
	}
	
	static function BuildOrderNo($user_id,$type){
	    $type_pre = '';
	    switch ($type){
	        case 'CHARGE':
	            $type_pre = 'C';
	            break;
	        case 'PAYMENT':
	            $type_pre = 'P';
	            break;
	        case 'LIVE_COURSE':
	            $type_pre = 'B';
	            break;
	        case 'LESSON':
	            $type_pre = 'L';
	            break;
			case 'COUPONS':
				$type_pre = 'K';
				break;
			case 'VIP':
				$type_pre = 'V';
				break;
	        default:
	            $type_pre = 'E';
				break;
	    }
	    $user_rand = self::UserRand($user_id);
	    return $type_pre.$user_rand;
	}
	
	static function UserRand($user_id){
	    $len = 5;
	    if (strlen($user_id)!=0){
	        $len = strlen($user_id);
	    }
	    $str1 = implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1)));
	    if (strlen($str1)<$len){
	        $len = strlen($str1);
	    }
	    $user = substr($user_id+substr($str1, 0, $len),0,5);
	    $str = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
	    $date = substr(date('Ymd'), 2);
	    return $date.$user.$str;
	}

	static function DayOfWeek($i) {
		if($i < 0 || $i > 6) {
			return '未知';
		}
		$days = array('星期天','星期一','星期二','星期三','星期四','星期五','星期六');
		return $days[$i];
	}
	
	/**
	 * 数组转XML
	 */
	static function ArrayToXML($data, $rootNodeName = 'data', $xml=null)
	{
	    // turn off compatibility mode as simple xml throws a wobbly if you don't.
	    if (ini_get('zend.ze1_compatibility_mode') == 1)
	    {
	        ini_set ('zend.ze1_compatibility_mode', 0);
	    }
	     
	    if ($xml == null)
	    {
	        $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
	    }
	     
	    // loop through the data passed in.
	    foreach($data as $key => $value)
	    {
	        // no numeric keys in our xml please!
	        if (is_numeric($key))
	        {
	            // make string key...
	            $key = "unknownNode_". (string) $key;
	        }
	         
	        // replace anything not alpha numeric
// 	        $key = preg_replace('/[^a-z]/i', '', $key);
	         
	        // if there is another array found recrusively call this function
	        if (is_array($value))
	        {
	            $node = $xml->addChild($key);
	            // recrusive call.
	            self::ArraytoXml($value, $rootNodeName, $node);
	        }
	        else
	        {
	            // add single node.
	            $value = htmlentities($value);
	            $xml->addChild($key,$value);
	        }
	         
	    }
	    // pass back as string. or simple xml object if you want!
	    return $xml->asXML();
	}
	
	/**
	 * XML转数组(CDATA)
	 * @param string $xmlstring XML字符串
	 * @return array XML数组
	 */
	static function XMLToArray($xmlstring) {
	    return json_decode(json_encode((array) simplexml_load_string($xmlstring,'SimpleXMLElement', LIBXML_NOCDATA)), true);
	}
	
	/*
	 * 汉字编码处理
	 */
	static function decodeUnicode($str) {
	    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function( '$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");' ), $str);
	}
	
}

?>
